/*
 * @(#)DefaultCookieHandler.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.usf.core.config.CookieConfig;


/**
 * @author Web Platform Development Team.
 */
public class DefaultCookieHandler implements CookieHandler {
	Log log = LogFactory.getLog(DefaultCookieHandler.class);

	/**
	 * @see com.nhncorp.usf.core.web.CookieHandler#getCookieValues(javax.servlet.http.Cookie[], com.nhncorp.usf.core.config.CookieConfig)
	 * @param cookies Cookie[]
	 * @param cookieConfig CookieConfig
	 * @return Map<String, String>
	 */
	public Map<String, String> getCookieValues(Cookie[] cookies, CookieConfig cookieConfig) {
		Map<String, String> cookieValues = new HashMap<String, String>();

		for (CookiePattern cookiePattern : cookieConfig.getCookiePatterns()) {
			String var = ((CookieNamePattern)cookiePattern).getVar();
			List<Cookie> filteredCookies = filter(cookies, cookiePattern);

			for (Cookie cookie : filteredCookies) {
				if ("*".equals(var)) {
					cookieValues.put(cookie.getName(), cookie.getValue());
				} else if (var.indexOf("*") > -1) {
					cookieValues.put(var.replaceAll("\\*", cookie.getName()), cookie.getValue());
				} else {
					cookieValues.put(var, cookie.getValue());
				}
			}
		}


		return cookieValues;
	}

	/**
	 * Filter.
	 *
	 * @param cookies the cookies
	 * @param cookiePattern the cookie pattern
	 *
	 * @return the list< cookie>
	 */
	protected List<Cookie> filter(Cookie[] cookies, CookiePattern cookiePattern) {
		if (cookies == null) {
			return Collections.emptyList();
		}

		List<Cookie> cookieList = new ArrayList<Cookie>();

		for (Cookie cookie : cookies) {
			if (cookiePattern.isValidate(cookie.getName())) {
				log.debug("cookie pattern matches with cookie name. " + cookiePattern.toString() + "[" + cookie.getName()
					+ "]");
				cookieList.add(cookie);
			}
		}

		return cookieList;
	}
}
